<template>
  <view class="clock-in" @tap="closeTip">
    <!-- 打卡页开始 -->
    <!-- 标题 -->
    <CustomHeader :scroll-top="scrollTop" :title="'习惯百日行'" />
    <!--  :class="{ headWhite: headWhite }" -->
    <!-- 公用头部 -->
    <ClockHeader :show-more-handle="false" :clock-detail="clockInInfo" :show-fold="true" />

    <!-- 输入打卡 -->
    <view v-if="isInputClock" class="input-clock">
      <view class="input-clock__content">
        <textarea v-model="inputClockContent" placeholder-style="color:#909399;font-size:16px" style="overflow: hidden" rows="1" maxlength="200" placeholder="说说今天的感受和收获吧～" />
        <!-- 录音展示 -->
        <view class="input-clock__voice">
          <!-- 录音 -->
          <view v-for="(item,index) in recordeList" :key="index" class="input-clock__voice--item" :class="{ 'only-one': recordeList.length === 1 }">
            <Audio :key="index" :src="item" :index="'audio' + index" @handleAudio="handleAudio" />
            <image class="delete-icon" :src="DELETE_ICON" @tap="deleteAudio(index)" />
          </view>
        </view>
        <!-- 图片展示 -->
        <view class="input-clock__images">
          <view v-for="(item, index) in uploadImgList" :key="index" class="input-clock__images--item">
            <image mode="aspectFill" lazy-load :src="item" @tap="preViewImg(item)" />
            <image class="delete-icon" :src="DELETE_ICON" @tap="deleteImage(index)" />
          </view>
        </view>
        <!-- 输入提示 -->
        <view class="input-clock__tips">
          <view class="input-clock__tips--wording">
            <text>请注意文明用语哦~</text>
            <image data-type="tip" :lazy-load="true" :src="WORDING_IMG" @tap="changeTipStatus" />
            <view v-if="showWordTip" class="input-clock__tips--wording__tooltip" @tap="changeTipStatus">审核发现不文明用语将作废该打卡记录。</view>
          </view>
          <view class="input-clock__tips--word-limit">{{ inputClockContent.length }}/200</view>
        </view>
        <!-- 其他输入选择 -->
        <view class="input-clock__other-way">
          <view class="input-clock__other-way--item" @tap="chooseImage">
            <image :lazy-load="true" class="icon" :src="UPLOAD_IMG" />
          </view>

          <view class="input-clock__other-way--item no-border" @tap="()=>{ startRecord() }">
            <image :lazy-load="true" class="icon" :src="RECORD_IMG" />
          </view>
        </view>
      </view>
      <!-- 提交按钮 -->
      <view class="input-clock__submit-btn submit-btn" :class="{'btn-disabled' : !inputClockFormVerify}" @tap="submitClock">提交</view>
    </view>

    <!-- 答题打卡 -->
    <view v-if="isAnswerClock" class="answer-clock">
      <view class="question-amount">
        <text>{{ questionIndex + 1 }}</text>
        / {{ questionContent.length }}
      </view>

      <view class="question-content">
        <!-- 题干 -->
        <view class="question-content__stem">
          {{
          cuurentQuestion && cuurentQuestion.title
          }}
        </view>
        <!-- 选项 -->
        <view v-for="(item,index) in cuurentQuestion && cuurentQuestion.option" :key="item.uuid" class="question-content__option">
          <image v-show="!item.checked" :lazy-load="true" :src="CHECK_ICON" class="question-content__option--check" @tap="changeCheckStatus(index,item.uuid)" />
          <image v-show="item.checked" :lazy-load="true" :src="CHECKED_ICON" class="question-content__option--checked" @tap="changeCheckStatus(index,item.uuid)" />
          <text class="question-content__option--title">{{ getIndexLabel(index) }}、{{ item.title }}</text>
          <image v-if="item.url" :lazy-load="true" :src="item.url" class="question-content__option--url" />
        </view>

        <!-- 解析 -->
        <view v-if="cuurentQuestion && cuurentQuestion.isAnalysis" class="question-content__analysis">
          <!-- header -->
          <view class="cloud-container">
            <view class="cloud-container-content">解析</view>
            <text class="left-cloud" />
            <text class="right-cloud" />
          </view>

          <!-- 答案解析 -->
          <view class="question-content__answer-analysis">
            <view class="question-content__answer-analysis--status" :class="answerStatusClass">{{ answerStatusText }}</view>
            <view class="question-content__answer-analysis--right">
              <text>
                <text>正确答案：</text>
                <text class="right">{{ cuurentRightAnswer }}</text>
              </text>
            </view>
            <view class="question-content__answer-analysis--my">
              <text>
                <text>我的答案：</text>
                <text :class="answerStatusClass">{{ cuurentQuestion.cuurentUserAnswer || "未选择" }}</text>
              </text>
            </view>
          </view>

          <!-- 解析内容 -->
          <view v-if="cuurentQuestion.analysis" class="question-content__analysis--content">{{ cuurentQuestion.analysis }}</view>
          <image v-if="cuurentQuestion.analysisUrl" class="question-content__analysis--image" :src="cuurentQuestion.analysisUrl" alt />
        </view>

        <!-- 按钮 -->
        <view class="question-content__btn">
          <!-- 1.未点击 完成时 显示完成
               2.点击完成后 显示上一步 下一步 在最后一题时显示提交
          -->
          <view v-show="cuurentQuestion && !cuurentQuestion.isAnalysis" :class="{'btn-disabled': !cuurentUserAnswer}" class="question-content__btn--submit" @tap="handleQuestion('analysis')">完成</view>
          <view v-show="cuurentQuestion && cuurentQuestion.isAnalysis">
            <!-- 
                在第一题 ：questionIndex === 0 -- inFristQuestion
                在最后一题 ： questionIndex === questionContent.length - 1 -- inLastQuestion
                题目长度大于1 questionContent.length > 1 -- notOnlyOneQuestion
            -->
            <view v-show="inFristQuestion && !inLastQuestion" class="question-content__btn--next-big" @tap="handleQuestion('next')">下一题</view>
            <view v-show="inLastQuestion && !notOnlyOneQuestion" class="question-content__btn--submit" @tap="handleQuestion('submit')">提交</view>
            <view v-show="!inFristQuestion && notOnlyOneQuestion" class="question-content__btn--group">
              <view class="question-content__btn--prev" @tap="handleQuestion('prev')">上一题</view>
              <view v-show="inLastQuestion" class="question-content__btn--submit" @tap="handleQuestion('submit')">提交</view>
              <view v-show="!inLastQuestion" class="question-content__btn--next" @tap="handleQuestion('next')">下一题</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 录音组件 -->
    <RecordSheet ref="RecordSheet" :stop-record-sheet="stopRecordSheet" :show.sync="showRecorder" @recordEnd="recordEnd" />
  </view>
</template>

<script >
import "./index.scss"
import ClockHeader from "@/components/clock-header/index.vue"
import RecordSheet from "@/components/record/index.vue"
import Audio from "@/components/record/audio.vue"
import CustomHeader from "_c/custom-header/index.vue"
import Taro from "@tarojs/taro"
import { AtCurtain } from "taro-ui-vue"
import { Component, Vue } from "vue-property-decorator"
import {
  themeDetail,
  submitClock,
  clockLogDetail,
  updateClock,
  reissueClock,
} from "@/libs/api/clock-in"
import {
  WORDING_IMG,
  UPLOAD_IMG,
  RECORD_IMG,
  WORDING_TOOLTIP_BGI,
  START_RECORDER_ICON,
  END_RECORDER_ICON,
  CHECK_ICON,
  CHECKED_ICON,
  DELETE_ICON,
  INPUT_CLOCK,
  ANSWER_CLOCK,
  NOT_SUBMIT_TIME,
  MAX_RECORD_LENGTH,
  MAX_IMAGE_LENGTH,
  ACTIVE_END,
} from "@/config/clock-in"
const QUESTION_OPTIONS_LABEL = {
  A: 0,
  B: 1,
  C: 2,
  D: 3,
  E: 4,
  F: 5,
  G: 6,
  H: 7,
  I: 8,
  J: 9,
  K: 10,
  0: "A",
  1: "B",
  2: "C",
  3: "D",
  4: "E",
  5: "F",
  6: "G",
  7: "H",
  8: "I",
  9: "J",
  10: "K",
}

export default {
  components: {
    ClockHeader,
    RecordSheet,
    Audio,
    CustomHeader,
  },
  data () {
    return {
      /* 打卡日签显示 */
      showShare: false,
      /* 输入打卡输入的内容 */
      inputClockContent: "",
      /* 文明用语提示图标 */
      WORDING_IMG: WORDING_IMG,
      /* 显示用语提示 */
      showWordTip: false,
      /* 上传图片图标 */
      UPLOAD_IMG: UPLOAD_IMG,
      /* 录音图标 */
      RECORD_IMG: RECORD_IMG,
      CHECK_ICON: CHECK_ICON,
      CHECKED_ICON: CHECKED_ICON,
      DELETE_ICON: DELETE_ICON,
      /* 打卡类型 1:输入 2: 答题 */
      clockInType: 1,
      /* 当前题目index */
      questionIndex: 0,
      /* 题目内容 */
      questionContent: [],
      /* 用户选择答案数组 */
      answerContent: [],
      /* 输入打卡 -- 上传图片列表 */
      uploadImgList: [],
      /* 打卡输入 -- 录音列表*/
      recordeList: [],
      /* 录音开始 */
      showRecorder: false,
      /* 打卡页内容信息 */
      clockInInfo: {},
      /* 当前学生选择的答案label */
      cuurentUserAnswer: "",
      playFlag: -1,

      /* 显示奖励弹窗 */
      showAward: false,
      showReissue: false,
      /* 提交loading */
      submitLoading: false,
      /* 日签信息 */
      clockSignInfo: {
        studentId: "",
        uuid: "",
      },
      uuid: "",
      /* 上传loading */
      uploadLoading: false,
      stopRecordSheet: false,
      scrollTop: 0,
    }
  },
  computed: {
    /* 图片数组是否都存在值 (全部上传完成) */
    isAllImg () {
      return this.uploadImgList.every((item) => {
        return item
      })
    },

    /* 当前在第一题 */
    inFristQuestion () {
      return this.questionIndex === 0
    },
    /* 当前作答在最后一题 */
    inLastQuestion () {
      return this.questionIndex === this.questionContent.length - 1
    },
    /* 题目长度大于1 */
    notOnlyOneQuestion () {
      return this.questionContent.length > 1
    },

    /* 补签状态 */
    isReissue () {
      return this.getParams.reissue
    },
    /* 编辑状态 */
    themeId () {
      return this.getParams.id
    },
    /* uuid */
    isEdit () {
      return this.getParams.uuid
    },
    /* 输入打卡验证表单 */
    inputClockFormVerify () {
      return (
        /* 文字输入是否大于10字 */
        this.inputClockContent.length >= 10 ||
        /* 上传图片数量是否大于1张 */
        this.uploadImgList.length >= 1 ||
        /* 上传图片数量是否大于1张*/
        this.recordeList.length >= 1
      )
    },
    /* 当前是输入打卡 */
    isInputClock () {
      return this.clockInType === INPUT_CLOCK
    },
    /* 当前是答题打卡 */
    isAnswerClock () {
      return this.clockInType === ANSWER_CLOCK
    },
    /* 解析答案状态 */
    answerStatusClass () {
      return this.cuurentQuestionIsRight ? "right" : "error"
    },
    /* 解析答案状态 */
    answerStatusText () {
      return this.cuurentQuestionIsRight ? "回答正确" : "回答错误"
    },
    /* 当前展示的题 */
    cuurentQuestion () {
      return this.questionContent && this.questionContent[this.questionIndex]
    },
    /* 当前在做题正确答案label */
    cuurentRightAnswer () {
      let ind
      this.cuurentQuestion.option.find((item, index) => {
        if (item.isAnswer) {
          ind = index
        }
        return item.isAnswer
      })
      return QUESTION_OPTIONS_LABEL[ind]
    },
    /* 当前题是否回答正确 */
    cuurentQuestionIsRight () {
      return this.cuurentRightAnswer === this.cuurentQuestion.cuurentUserAnswer
    },
  },
  onPageScroll ({ scrollTop }) {
    this.scrollTop = scrollTop
  },
  created () {
    this.getClockInInfo()
  },
  onHide () {
    this.stopRecordSheet = true
    this.playFlag = -1
  },
  methods: {
    /* 关闭tip */
    closeTip ({ target: { dataset } }) {
      if (dataset.type === "tip") return
      this.showWordTip = false
    },

    /* 转换label */
    getIndexLabel (index) {
      return QUESTION_OPTIONS_LABEL[index]
    },

    /* 预览图片 */
    preViewImg (item) {
      Taro.previewImage({
        urls: this.uploadImgList,
        current: item,
      })
    },
    /* 删除音频 */
    deleteAudio (index) {
      console.log(index)
      let a = this.recordeList
      this.recordeList = []
      a.splice(index, 1)
      setTimeout(() => {
        this.recordeList = a
        console.log(this.recordeList)
      })
    },
    /* 删除图片 */
    deleteImage (index) {
      this.uploadImgList.splice(index, 1)
    },
    /* 播放音频 */
    handleAudio (index) {
      console.log(index)
      this.playFlag = index
      this.$store.commit('setMediaVideoFlag',index)
    },
    /* methods */
    /* 重新打卡 数据回显 */
    async getClockDetail () {
      let {
        data: { commit_text, commit_img, commit_audio, commit_choose_question },
      } = await clockLogDetail({ uuid: this.uuid })

      this.inputClockContent = commit_text
      commit_img && (this.uploadImgList = commit_img)
      commit_audio && (this.recordeList = commit_audio)
      commit_choose_question &&
        (commit_choose_question = commit_choose_question)
      Array.isArray(commit_choose_question) &&
        (this.answerContent = commit_choose_question.map((item, index) => {
          const option = this.questionContent[index].option
          option[QUESTION_OPTIONS_LABEL[item]].checked = true
          this.$set(this.questionContent[index], "option", option)
          this.$set(this.questionContent[index], "oldAnswer", item)
          return {
            label: item,
          }
        }))
      this.cuurentUserAnswer =
        this.cuurentQuestion.cuurentUserAnswer ||
        this.cuurentQuestion.oldAnswer
      this.$forceUpdate()
      console.log(this.answerContent, "this.answerContent")
    },
    /* 答题打卡 -- 切换题目 */
    handleQuestion (type) {
      switch (type) {
        case "submit":
          this.submitClock()
          break
        case "next":
          console.log("next")
          this.questionIndex < this.questionContent.length &&
            this.questionIndex++
          this.cuurentUserAnswer =
            this.cuurentQuestion.cuurentUserAnswer ||
            this.cuurentQuestion.oldAnswer
          break
        case "prev":
          console.log("prev")
          this.questionIndex > 0 && this.questionIndex--
          break
        case "analysis":
          console.log("analysis")
          if (!this.cuurentUserAnswer)
            return Taro.showToast({ title: "未做答", icon: "none" })
          this.questionContent[this.questionIndex].isAnalysis = true
          this.questionContent[
            this.questionIndex
          ].cuurentUserAnswer = this.cuurentUserAnswer

          break
      }
    },
    /* 答题打卡选择选项 */
    changeCheckStatus (index, uuid) {
      if (this.cuurentQuestion.isAnalysis) return
      const option = this.questionContent[this.questionIndex].option
      if (!option[index].checked) {
        option.map((item) => {
          item.checked = false
        })
        option[index].checked = true

        this.answerContent[this.questionIndex] = {
          uuid,
          index,
          label:
            this.questionContent[this.questionIndex].cuurentUserAnswer ||
            QUESTION_OPTIONS_LABEL[index],
        }
        this.cuurentUserAnswer = QUESTION_OPTIONS_LABEL[index]
      } else {
        option[index].checked = false
        this.cuurentUserAnswer = undefined
        this.answerContent[this.questionIndex] = { uuid, index: undefined }
      }
      this.$set(this.questionContent[this.questionIndex], "option", option)
      this.$forceUpdate()
    },
    /* 获取打卡详情信息 */
    async getClockInInfo () {
      try {
        const { data } = await themeDetail({ id: this.themeId })
        /* data 需要添加的阻断
      isAnalysis: boolean, 
    */
        this.clockInInfo = data
        data.question_content &&
          (data.question_content = JSON.parse(data.question_content))
        /* 临时判断 需要更换判断条件 */
        Array.isArray(data.question_content)
          ? (this.clockInType = ANSWER_CLOCK)
          : (this.clockInType = INPUT_CLOCK)
        /*
      * question_content 需要添加的字段
       check: boolean
       label: string
     */
        data.content = JSON.parse(data.content)
        Array.isArray(data.question_content) &&
          (this.questionContent = data.question_content.map((item, index) => {
            return {
              ...item,
              isAnalysis: false,
            }
          }))
        console.log(this.questionContent, "questionContent")
        /* 在编辑状态 */
        this.uuid = data.uuid
        this.isEdit && this.getClockDetail()
      } catch (error) {
        console.log(error, "errorerror")
        /* 活动结束返回首页 */
        if (error.status_code === ACTIVE_END) {
          Taro.showToast({
            title: "活动已结束",
            icon: "none",
            duration: 2000,
          })
          setTimeout(() => {
            Taro.navigateBack({
              delta: 1,
              fail: () => {
                Taro.redirectTo({
                  url: `/pages/theme-detail/index?id=${this.themeId}`,
                })
              },
            })
          }, 2000)
        }
        console.log(error, "errorerrorerror")
      }
    },
    /* 打卡完成事件 */
    onClose () {
      /* 需要判断前一个页面是不是主题详情 是返回上一级 不是跳转到主题详情 */
      const pageSta = Taro.getCurrentPages()
      Taro.setStorageSync('clockOver', 1)
      if (pageSta[pageSta.length - 2].route === 'pages/theme-detail/index') {
        Taro.navigateBack({
          delta: 1
        })
      } else {
        Taro.redirectTo({
          url: `/pages/theme-detail/index?id=${this.themeId}&clockOver=1`,
          success: () => {
            Taro.eventCenter.trigger("handleClockOver", 1)
          }
        })
      }
    },
    /* 提交打卡 */
    async submitClock () {
      if (!this.clockInInfo.is_answer && !this.inputClockFormVerify) return
      if (this.submitLoading) return
      this.submitLoading = true

      const data = {
        theme_id: this.themeId,
        uuid: this.uuid /* 编辑时存在 */,
        commit_text: this.inputClockContent,
        commit_img: JSON.stringify(this.uploadImgList),
        commit_audio: JSON.stringify(this.recordeList),
        commit_choose_question: JSON.stringify(
          this.answerContent.reduce((all, item) => {
            return [...all, item.label]
          }, [])
        ),
      }
      let promise = this.isReissue
        ? reissueClock(data)
        : this.isEdit
          ? updateClock(data)
          : submitClock(data)
      promise
        .then((r) => {
          this.clockSignInfo = {
            studentId: this.clockInInfo.student_id,
            uuid: r.data,
          }
          this.onClose()

          /* Taro.showToast({ title: "弹出打卡日签" }); */
          /* this.createClockInviting(); */
          this.submitLoading = false
        })
        .catch((err) => {
          console.log(err, "errerrerr")
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000,
            complete: () => {
              /* 不在打卡时段返回主题详情页面 */
              err.status_code === NOT_SUBMIT_TIME &&
                setTimeout(() => {
                  Taro.redirectTo({
                    url: `/pages/theme-detail/index?id=${this.themeId}`,
                  })
                }, 1000)
            },
          })

          this.submitLoading = false
        })
    },
    /* 开始录音 */
    startRecord () {
      if (this.showRecorder) return
      this.playFlag = -1
      this.recordeList.length < MAX_RECORD_LENGTH
        ? (this.showRecorder = true)
        : Taro.showToast({
          title: `最多上传${MAX_RECORD_LENGTH}条语音哦~`,
          icon: "none",
        })
    },
    /* 录音结束事件 */
    recordEnd ({ duration, tempFilePath }) {
      this.showRecorder = false
      Taro.showLoading({
        title: "文件上传中",
        mask: true,
      })
      this.uploadFile(tempFilePath, ({ url, code }, res, data) => {
        this.recordeList.push(url)
        Taro.hideLoading()
      })
    },
    /* 选择图片 */
    chooseImage () {
      if (this.uploadLoading) return

      this.uploadLoading = true
      if (this.uploadImgList.length >= MAX_IMAGE_LENGTH) {
        this.uploadLoading = false
        return Taro.showToast({
          title: `最多上传${MAX_IMAGE_LENGTH}张图片哦~`,
          icon: "none",
        })
      }
      Taro.chooseImage({
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
        count: MAX_IMAGE_LENGTH - this.uploadImgList.length,
        success: (res) => {
          Taro.showLoading({
            title: "文件上传中",
            mask: true,
          })
          if (!this.uploadFileSizeIsLegal(res.tempFiles, { maxSize: 1 })) {
            Taro.hideLoading()
            setTimeout(() => {
              Taro.showToast({
                title: "上传图片中有超过最大图片大小限制1M",
                icon: "none",
              })
            }, 200)

            this.uploadLoading = false
            return
          }
          this.inUpLoadFile(res.tempFilePaths)
          /*  const length = this.uploadImgList.length */
          /* for (const i in res.tempFilePaths) {
            this.uploadFile(
              res.tempFilePaths[i],
              ({ url, code }, res, data) => {
                this.$set(this.uploadImgList, ~~i + length, url)
                if (this.isAllImg) {
                  Taro.hideLoading()
                  this.uploadLoading = false
                }
              }
            )
          } */
        },
        fail: (e) => {
          Taro.hideLoading()
          this.uploadLoading = false
        },
      })
    },
    inUpLoadFile (urls) {
      if (!urls.length) {
        this.uploadLoading = false
        Taro.hideLoading()
        return
      }
      let url = urls.splice(0, 1)
      url = url.length && url[0]
      this.uploadFile(
        url,
        ({ url: uploadUrl }) => {
          this.uploadImgList.push(uploadUrl)
          this.inUpLoadFile(urls)
        },
        /* 上传失败处理 */
        () => {
          this.uploadLoading = false
          Taro.showToast({
            title: '部分图片上传失败',
            icon: 'none',
          })
        }
      )
    },
    /* 改变用语提示显示状态 */
    changeTipStatus () {
      this.showWordTip = !this.showWordTip
    },
    /* 打开邀请弹窗 */
    createClockInviting () {
      this.showShare = true
    },
    /* 关闭弹窗 */
    close () {
      this.showShare = false
    },
  },
};
</script>
